package edu.neusoft.yiqibike.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import edu.neusoft.yiqibike.common.datasource.TargetDataSource;
import edu.neusoft.yiqibike.common.entity.mysql.User;
import edu.neusoft.yiqibike.common.exception.ArgumentVerifyException;
import edu.neusoft.yiqibike.dao.mapper.UserMapper;
import edu.neusoft.yiqibike.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * User：lyc
 * Date：2017-12-15
 * Time：17:55
 * Description：
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    @TargetDataSource(name = "ds2")
    public Page<User> getUserList(Page<User> page) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        if (page != null && !CollectionUtils.isEmpty(page.getCondition())) {
            Map<String, Object> condition = page.getCondition();
            String nickname = (String) condition.get("nickname");
            if (StringUtils.isNotEmpty(nickname)) {
                wrapper.like("nickname", nickname, SqlLike.RIGHT);
            }
        }
        List<User> userList = baseMapper.selectByPage(page, wrapper);
        userList = userList.stream().sorted(Comparator.comparing(User::getCreateTime)).collect(Collectors.toList());
        page.setRecords(userList);
        return page;
    }

    @Override
    @Transactional
    @TargetDataSource(name = "ds2")
    public void invertIsEnable(Long uid, Integer isEnable) {
        if (1 == isEnable) {
            isEnable = -1;
        } else if (-1 == isEnable) {
            isEnable = 1;
        } else {
            throw new ArgumentVerifyException("【用户可用状态】：非法");
        }
        baseMapper.invertIsEnable(uid, isEnable);
    }
}
